package com.ljb.utilslibrary.commUtils;

import android.app.Activity;
import android.os.Process;

import java.util.ArrayList;
import java.util.List;

/**
 * Activity的管理器在Activity的基类中调用添加和移除的方法,在需要关闭界面的时候调用其他方法
 * Created by lijianbin on 2017/1/20.
 */
public class ActivityCollector {
    private static List<Activity> activities = new ArrayList<>();

    private ActivityCollector() {
    }

    /**
     * 将当前Activity添加到管理器中
     *
     * @param activity 当前的Activity,传this就可以
     */
    public static void addActivity(Activity activity) {
        activities.add(activity);
    }

    /**
     * 将当前Activity从管理器中移除
     *
     * @param activity 当前的Activity,传this就可以
     */
    public static void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    /**
     * 关闭所有界面
     */
    public static void finishAll() {
        for (Activity activity : activities) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /**
     * 关闭所有界面,杀掉应用进程
     */
    public static void finishProcess() {
        finishAll();
        Process.killProcess(Process.myPid());
    }

    /**
     * 关闭当前Activity之前的所有Activity
     */
    public static void finishBefore() {
        for (int i = 0; i < activities.size() - 1; i++) {
            Activity activity = activities.get(i);
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }
}
